<?php 
require_once(HELPERS_INCLUDE_PATH.'HTML/SimpleHtmlDom.php');
class AdImport extends Object
{
	public $UserId;
	public $Frequency;
	public $DateCreated;
	public $DateLastRun;
	public $URL;
	public $HtmlSource;
	public $AutoPublish;
	public $AutoDelete;
	public $FeedFilename;
	public $Active;
	public $Found;
	public $Imported;
	public $Updated;
	public $ImportConverts;
	public $UserAds;
	public $Out;
	
	public function AdImport($values = '')
	{ 
		self::setDataTable('am_Import');
		if(is_array($values))
		{ self::setValues($values); }
	}

	public function getUserId() { return intval($this->UserId); }
	public function getFrequency() { return intval($this->Frequency); }
	public function getDateCreated()
	{ 
		if($format != '')
		{ return self::formatDateTime($this->DateCreated, $format); }
		else
		{ return $this->DateCreated; }
	}
	public function getDateLastRun()
	{ 
		if($format != '')
		{ return self::formatDateTime($this->DateLastRun, $format); }
		else
		{ return $this->DateLastRun; }
	}
	public function getImportConverts()
	{
		self::loadImportConverts();
		return $this->ImportConverts;
	}
	public function getHtmlSource() { return intval($this->HtmlSource); }
	public function getAutoPublish() { return intval($this->AutoPublish); }
	public function getAutoDelete() { return intval($this->AutoDelete); }
	public function getFound() { return intval($this->Found); }
	public function getImported() { return intval($this->Imported); }
	public function getUpdated() { return intval($this->Updated); }
	
	public function setUserId($val) { $this->UserId=intval($val); }
	public function setFrequency($val) { $this->Frequency=intval($val); }
	public function setHtmlSource($val) { $this->HtmlSource=intval($val); }
	public function setAutoPublish($val) { $this->AutoPublish=intval($val); }
	public function setAutoDelete($val) { $this->AutoDelete=intval($val); }
	
	public function setFound($val) { $this->Found=intval($val); }
	public function setImported($val) { $this->Imported=intval($val); }
	public function setUpdated($val) { $this->Updated=intval($val); }
	
	public function runImport()
	{
		$this->Out = self::getSaveFeed();
		if(self::getFeedFilename() != '')
		{
			$this->Out .= self::prepareFeed();
			$this->Out .= self::convertFeed();
			$this->Out .= self::importFeed();
			self::setDateLastRun(date('Y-m-d h:i:s'));
			self::update();
		}
		return $this->Out;
	}
	
	function getSaveFeed($elementId=0)
	{
		$out = '';
		if(self::getURL() != '')
		{
			$xmlStr = file_get_contents(self::getURL());
			if($xmlStr)
			{
				if(!(file_exists(ADS_IMPORT_PATH.'download/')))
				{ mkdir(ADS_IMPORT_PATH.'download/'); }
				$postfix = date('Y-m-d-hi');
				switch(self::getFrequency())
				{
					case 0:
						$postfix = date('Y-m-d');
					break;
					case 1:
						$postfix = date('Y-m-d-h');
					break;
				}
				if(self::getHtmlSource() > 0)
				{ self::setFeedFilename(self::getUserId().'_'.$postfix.'_'.$elementId.'.htm'); }
				else
				{ self::setFeedFilename(self::getUserId().'_'.$postfix.'.xml'); }
				file_put_contents(ADS_IMPORT_PATH.'download/'.self::getFeedFilename(), $xmlStr);
				$out = '<br />Feed Downloaded:'.self::getURL().' - >'.self::getFeedFilename();
			}
			else
			{ $out = '<br />URL'.self::getURL().' Does not respond'; }
		}
		else
		{ $out = '<br />No URL Defined'; }
		return $out;
	}
	
	function prepareFeed()
	{
		$out = 0;
		if(file_exists(ADS_IMPORT_PATH.'download/'.self::getFeedFilename()))
		{
			if(!(file_exists(ADS_IMPORT_PATH.'prepare/')))
			{ mkdir(ADS_IMPORT_PATH.'prepare/'); }
			
			copy(ADS_IMPORT_PATH.'download/'.self::getFeedFilename(), ADS_IMPORT_PATH.'prepare/'.self::getFeedFilename());
			$out = '<br />Feed Prepared:'.ADS_IMPORT_PATH.'prepare/'.self::getFeedFilename();
		}
		else
		{ $out = '<br />Feed not found at:'.ADS_IMPORT_PATH.'download/'.self::getFeedFilename(); }
		return $out;
	}
	
	function convertFeed($elementId=0)
	{
		$out = 0;
		if(file_exists(ADS_IMPORT_PATH.'prepare/'.self::getFeedFilename()))
		{
			if(!(file_exists(ADS_IMPORT_PATH.'converted/')))
			{ mkdir(ADS_IMPORT_PATH.'converted/'); }

			if(self::getHtmlSource() > 0)
			{ $htmlStr = file_get_contents(ADS_IMPORT_PATH.'prepare/'.self::getFeedFilename()); }
			else
			{ $xmlStr = file_get_contents(ADS_IMPORT_PATH.'prepare/'.self::getFeedFilename());}
			
			if($htmlStr)
			{
				if($elementId > 0)
				{
					if(is_array(self::getImportConverts()) && ($elementId > 0))
					{ $arrStr = self::convertHTML($htmlStr); }
					file_put_contents(ADS_IMPORT_PATH.'converted/'.self::getFeedFilename(), $arrStr);
					return $arrStr;
				}
				else
				{
					if(is_array(self::getImportConverts()) && ($elementId > 0))
					{ $htmlStr = self::convertHTML($htmlStr); }
					file_put_contents(ADS_IMPORT_PATH.'converted/'.self::getFeedFilename(), $htmlStr);
					$out = '<br />Feed Converted:'.ADS_IMPORT_PATH.'converted/'.self::getFeedFilename();
				}
			}
			
			if($xmlStr)
			{
				if(is_array(self::getImportConverts()))
				{ $xmlStr = self::convertXml($xmlStr); }
				file_put_contents(ADS_IMPORT_PATH.'converted/'.self::getFeedFilename(), $xmlStr);
				$out = '<br />Feed Converted:'.ADS_IMPORT_PATH.'converted/'.self::getFeedFilename();
			}
		}
		else
		{ $out = '<br />Feed not found at:'.ADS_IMPORT_PATH.'prepare/'.self::getFeedFilename(); }
		return $out;
	}
	
	function importFeed()
	{
		$out = '';
		if(self::getFeedFilename() != '')
		{
			if(file_exists(ADS_IMPORT_PATH.'converted/'.self::getFeedFilename()))
			{
				$out .= '<br />Importing Feed:'.ADS_IMPORT_PATH.'converted/'.self::getFeedFilename();
				
				set_time_limit(3600);
				
				if(self::getHtmlSource() > 0)
				{
					//$htmlStr = file_get_contents(ADS_IMPORT_PATH.'converted/'.self::getFeedFilename());
					$html = file_get_html(ADS_IMPORT_PATH.'converted/'.self::getFeedFilename());
					$adListHTML = $html->find('section.resultlist article');
					$i=0;
					foreach($adListHTML as $adHTML)
					{
						$link = $adHTML->find('section.info a');
						$elements[$i]['source'] = $link[0]->href;
						$elements[$i]['title'] = $link[0]->innertext; 
						$i++;
					}
					if($elements)
					{
						$i=0;
						foreach($elements as $element)
						{
							unset($objArray);
							echo '<br />Getting content on '.$element['title'].' from:'.$element['source'].'<br />';
							$sparts = explode('=', $element['source']);
							if(is_array($sparts))
							{
								if(intval($sparts[1]) > 0)
								{
									$id = $sparts[1];
									self::setURL($element['source']);
									$out .= self::getSaveFeed($id);
									$out .= self::prepareFeed();
									//$out .= self::convertFeed($id);
									$objArray = self::convertFeed($id);
									if(is_array($objArray))
									{
										$objArray['AdList']['Ad']['Title'] = $element['title'];
										$objArray['AdList']['Ad']['RemoteId'] = $id;
										$objArray['AdList']['Ad']['RemoteUrl'] = $element['source'];
										//print_r($objArray);
										//echo '<br /><hr />';
									}
								}
							}
							if(is_array($objArray['AdList']['Ad']))
							{
								$adList[$i] = $objArray['AdList']['Ad'];
								$i++;
							}
						}
					}
				}
				else
				{
					$xmlStr = file_get_contents(ADS_IMPORT_PATH.'converted/'.self::getFeedFilename());
					$adList = new SimpleXMLElement($xmlStr);
				}
				unset($adListAds);
				if(is_object($adList))
				{ $adListAds = $adList->children(); }
				elseif(is_array($adList))
				{ $adListAds = $adList; }
				
				if($adListAds)
				{
					global $ac;
					global $adc;
					global $txt;
					
					self::setFound(count($adListAds));
					
					if(self::getAutoDelete())
					{ 
						$this->UserAds = $adc->getUserAds(self::getUserId()); 
						foreach($this->UserAds as $ua)
						{
							if($ua->getRemoteId() > 0)
							{ $deleteUserAds[$ua->getRemoteId()] = $ua->getId(); }
						}
						echo 'found UserAds:<br />';
						print_r(array_keys($this->UserAds));
					}
					//echo '<br />Current userAds:'.count($deleteUserAds);
					//print_r($deleteUserAds);
					foreach($adListAds as $adListAd)
					{
						$out .= '<br />Importing Element';
						unset($params);
						unset($DownloadImagesXml);
						unset($DownloadImages);
						unset($images);
						
						$desc = '';
						if(is_object($adList))
						{
							if(is_object($adListAd->ImagesURL[0]))
							{
								$DownloadImagesXml = $adListAd->ImagesURL[0]->children();
								$i=0;
								if($DownloadImagesXml)
								{
									foreach($DownloadImagesXml as $imgUrl)
									{
										if($imgUrl->getName() == 'ImageURL')
										{ 
											$DownloadImages[$i] = (string)$imgUrl;
											$i++;
										}
									}
								}
							}
							unset($adListAd->ImagesURL);
							unset($adListAd->Ignore);
						}
						elseif(is_array($adList))
						{ 
							$DownloadImages = $adListAd['ImagesURL'];
							unset($adListAd['Parameters']);
							unset($adListAd['ImageParameters']);
							unset($adListAd['ImagesURL']);
						}
						
						$out .= ' with '.count($DownloadImages).' Images:';
						
						if(is_object($adList))
						{ $params = get_object_vars($adListAd); }
						else
						{ $params = $adListAd; }
						
						foreach(array_keys($params) as $objectVar)
						{
							//echo 'checking:'.$objectVar;
							//echo 'value:'.$params[$objectVar];
							
							switch($objectVar)
							{
								case 'Title':
								case 'TitleEn':
								case 'Description':
								case 'DescriptionEn':
								case 'PriceCurrency':
								case 'Model':
								case 'SerialNo':
								case 'ContactEmail':
								case 'ContactName':
								case 'ContactCompany':
								case 'ContactMob':
								case 'ContactPhone':
								case 'ContactWeb':
								case 'LocationAddress':
								case 'LocationZip':
								case 'LocationCity':
								case 'LocationCountry':
								//Ad Vehicle
								case 'RegistrationNo':
								case 'RegNo':
								case 'CabinType':
								case 'SuspensionFront':
								case 'SuspensionRear':
								case 'ShaftType':
								//Ad Vehicle End
								//Ad VehicleLight
								case 'ColorTxt':
								case 'GearTypeTxt':
								case 'WheelDriftTxt':
								//Ad VehicleLight End
								//Ad Transport
								case 'FromCountry':
								case 'FromCity':
								case 'FromZip':
								case 'ToCountry':
								case 'ToCity':
								case 'ToZip':
								//Ad Transport End
								//Ad Employement
								//Ad Employement End
									if(is_array($params[$objectVar]))
									{ 
										$text = '';
										foreach($params[$objectVar] as $var)
										{ $text .= self::formatText($var).' '; }
										unset($params[$objectVar]);
										if($text != '')
										{ $params[$objectVar] = $text; }
									}
									else
									{ $params[$objectVar] = self::formatText($params[$objectVar]); }
								break;
								case 'RemoteId':
								case 'RemoteTypeId':
								case 'TypeId':
								case 'RemoteCatId':
								case 'CatId':
								case 'BrandId':
								case 'ModId':
								case 'IsBuying':
								case 'IsNew':
								case 'PriceDisplay':
								case 'Year':
								case 'LengthUsed':
								case 'Weight':
								case 'Power':
								case 'Volume':
								//Ad Vehicle
								case 'AdVehicleId':
								case 'EuApproved':
								case 'MaintenanceDoc':
								case 'AirCondition':
								case 'AditionalHydra':
								case 'CeMarked':
								case 'ConformityDeclaration':
								case 'AutoTrans':
								case 'TrailerBreak':
								case 'LoadCapacityVolume':
								case 'LoadCapacityWeight':
								case 'Wheelbase':
								case 'TailLift':
								case 'InsideLength':
								case 'InsideWidth':
								case 'ClutchlessTurningGear':
								case 'SpeedGear':
								case 'SpringCottage':
								case 'SuspFrontAxle':
								case 'IsTracked':
								//Ad Vehicle End
								//Ad VehicleLight
								/* Main values */
								case 'ColorId':
								case 'CountSeats':
								case 'CountDoors':
								case 'FuelType':
								case 'GearType':
								case 'WheelDrift':
								case 'OwnersCount':
								case 'TaxClass':
								case 'TechApproved':
								/* Equipement */
								/* Safety values */
								case 'ABS':
								case 'AirbagFront':
								case 'AirbagSide':
								case 'Alarm':
								case 'DiffLock':
								case 'TractionControll':
								case 'AntiSlipRegulation':
								case 'EngineImmobilizer':
								case 'SteelBeams':
								case 'RemovableHitch':
								case 'DieselParticleFilter':
								/* Equipement */
								case 'AllSeasonTires':
								case 'Hitch':
								case 'CargoHolder':
								case 'LightAlloyWheelsSummer':
								case 'LightAlloyWheelsWinter':
								case 'AirSuspension':
								case 'MetallicPaint':
								case 'LevelControll':
								case 'ParkingSensorFront':
								case 'ParkingSensorRear':
								case 'WheelsSummer':
								case 'WheelsWinter':
								case 'RoofRails':
								case 'XenonHeadlight':
								/* Comfort */
								case 'AirCon':
								case 'BaggageCover':
								case 'CdChanger':
								case 'CruiseControl':
								case 'PartialLeather':
								case 'DVD':
								case 'PowerSeat':
								case 'PowerSeatMemory':
								case 'PowerMirrors':
								case 'PowerWindows':
								case 'TintedGlass':
								case 'Handsfree':
								case 'KeylessGo':
								case 'TripComputer':
								case 'CentreArmrest':
								case 'EngineHeater':
								case 'MultifunctionSteering':
								case 'GPS':
								case 'HeatedSeats':
								case 'RadioCD':
								case 'RainSensor':
								case 'CentralLock':
								case 'Servo':
								case 'LeatherInterior':
								case 'SportSeats':
								case 'Sunroof':
								case 'Tv':
								//Ad VehicleLight End
								//Ad Transport
								case 'Length':
								case 'Width':
								case 'StandingOrder':
								//Ad Transport
								//Ad Employement
								case 'IsFullTime':
								case 'EmploymentType':
								case 'CountryPart':
								case 'Diploma':
								//Ad Employement End
									$params[$objectVar] = intval($params[$objectVar]);
								break;
								case 'PriceLocal':
								case 'PriceGlobal':
									$params[$objectVar] = intval($params[$objectVar]);
								break;
								//Ad Vehicle
								case 'EuApprovedDate':
								case 'TechApprovedDate':
								case 'YearReg':
								case 'FirstTimeReg':
									if(self::formatDateTime($params[$objectVar], 'd.m.Y') != date('d.m.Y', 0))
									{ $params[$objectVar] = self::formatDateTime($params[$objectVar], 'd.m.Y'); }
								//Ad Vehicle End
								//Ad Transport
								case 'FromDate':
								case 'ToDate':
								//Ad Transport End
								//Ad Employement
								case 'DateStart':
								case 'DateDue':
								//Ad Employement End
									if(self::formatDateTime($params[$objectVar], 'd.m.Y') != date('d.m.Y', 0))
									{ $params[$objectVar] = self::formatDateTime($params[$objectVar], 'd.m.Y'); }
								break;
								default:
									if(self::getHtmlSource() > 0)
									{ unset($params[$objectVar]); }
								break;
							}
						}
						
						if(($params['RemoteTypeId'] > 0) || ($params['RemoteCatId'] > 0))
						{ $params = self::findTypeCatId($params); }
						//echo '<br />TypeIdCatId:';
						
						//echo 'setting $newAd with params:';
						//print_r($params);
						$newAd 	= new Ad($params);
						$newAd->setUserId(self::getUserId());
						//echo '<br />';
						if(isset($deleteUserAds[$newAd->getRemoteId()]))
						{ 
							unset($deleteUserAds[$newAd->getRemoteId()]);
							//echo '<br />Keeping Ad:'.$newAd->getRemoteId().' - current count to delete:'.count($deleteUserAds);
						}
						$adc->setCurrentAdId(0);
						$id = self::checkIfExists($newAd);
						//echo '<hr /><br />AdObject:'.$id.'<br />';
						$BrandId = self::findBrandId($newAd);
						//print_r($newAd);
						if($id == 0)
						{
							$newAd->makeTitle();
							$newAd->setBrandId($BrandId);
							$adc->setFrontend(1);
							//$adc->setCurrentAdTypeId(0);
							//$adc->setCurrentAdCatId(0);
							if(($newAd->getTypeId() > 0) && ($newAd->getCatId() > 0) && ($newAd->getBrandId() > 0))
							{ 
								$newAd->insert(); 
								$out .= '<br />Adding new Element ID:'.$newAd->getId();
								$this->Imported = (self::getImported() + 1);
							}
							else
							{
								$out .= '<br />Element Missing Parameters RemoteId:'.$newAd->getRemoteId();
								if(!($newAd->getTypeId() > 0))
								{ $out .= '<br />-MainCategory Missing'; }
								if(!($newAd->getCatId() > 0))
								{ $out .= '<br />-SubCategory Missing'; }
								if(!($newAd->getBrandId() > 0))
								{ $out .= '<br />-BrandId Missing'; }
								
							}
						}
						else
						{ 
							$newAd->setId($id);
							if($BrandId != $newAd->getBrandId())
							{
								$newAd->makeTitle();
								$newAd->setBrandId($BrandId);
							}
							$out .= '<br />Updating existing Element ID:'.$id;
							$this->Updated = (self::getUpdated() + 1);
						}
						
						if($newAd->getId() > 0)
						{ 
							$adc->setFrontend(0);
							$adc->setCurrentAdId($newAd->getId());
							if(is_object($adc->getCurrentAd()))
							{
								$adc->CurrentAd->setTypeId($newAd->getTypeId());
								$adc->CurrentAd->setCatId($newAd->getCatId());
								$adc->CurrentAd->setBrandId($newAd->getBrandId());
								$adc->CurrentAd->makeTitle(1);
								//echo '<br />$adc->CurrentAd<br />';
								//print_r($adc->CurrentAd);
								$adc->CurrentAd->updateValues($params);
								$adc->CurrentAd->setDataChanged(1);
								
								$adUser = $ac->getUser(self::getUserId());
								$userdetails = new UserDetails($adUser);
								
								if($adc->CurrentAd->getContactEmail() == '')
								{ $adc->CurrentAd->setContactEmail($adUser->getEmail()); }
								
								if($adc->CurrentAd->getContactName() == '')
								{ $adc->CurrentAd->setContactName($userdetails->getName().' '.$userdetails->getLastname()); }
								
								if($adc->CurrentAd->getContactCompany() == '')
								{ $adc->CurrentAd->setContactCompany($userdetails->getCompany()); }
								
								if($adc->CurrentAd->getContactWeb() == '')
								{ $adc->CurrentAd->setContactWeb($userdetails->getWww()); }
								
								if($adc->CurrentAd->getContactMob() == '')
								{ $adc->CurrentAd->setContactMob($userdetails->getMob()); }
								
								if($adc->CurrentAd->getContactPhone() == '')
								{ $adc->CurrentAd->setContactPhone($userdetails->getPhone()); }
								
								if($adc->CurrentAd->getLocationAddress() != $userdetails->getAddress())
								{ $adc->CurrentAd->setLocationAddress($userdetails->getAddress()); }
								
								if($adc->CurrentAd->getLocationZip() !=  $userdetails->getZip(4))
								{ $adc->CurrentAd->setLocationZip($userdetails->getZip(4)); }
								
								if($adc->CurrentAd->getLocationCity() != $userdetails->getCity())
								{ $adc->CurrentAd->setLocationCity($userdetails->getCity()); }
								
								if($adc->CurrentAd->getLocationCountry() == '')
								{ $adc->CurrentAd->setLocationCountry($userdetails->getCountry()); }
								
								//echo '<br />Updating';
								$adc->CurrentAd->setIsValid(1);
								$adc->CurrentAd->update();
								$out .= '<br />Values Updated';
								//print_r($adc->CurrentAd);
								//echo '<br />Values Updated $newAd->getId():'.$newAd->getId();
								
								$adc->CurrentAd->setItemLoaded('image', 0);
								$adc->CurrentAd->setItemLoaded('images', 0);
								
								$weekday = date("N");
								$fimgId = $adc->CurrentAd->getImage()->getId();
								
								//Brisanje svih slika petkom ako ima slika od prije i ako se moze downloadirati
								if(($fimgId > 0) && ($weekday == 100) && is_array($DownloadImages))
								{
									$adc->CurrentAd->deleteImage($fimgId);
									
									$curImages = $adc->CurrentAd->getImages();
									if(is_array($curImages))
									{
										foreach(array_keys($curImages) as $imgId)
										{ 
											$adc->CurrentAd->deleteImage($imgId); 
											echo '<br />$adc->CurrentAd->deleteImage('.$imgId.')';
										}
									}
									$adc->CurrentAd->setItemLoaded('images', false);
								}
								//Haplodiraj slike ako su izbrisane ili ako nema nikako slika
								if(($fimgId == 0) || (($fimgId > 0) && ($weekday == 100) && is_array($DownloadImages)))
								{
									if(is_array($DownloadImages))
									{
										foreach($DownloadImages as $image)
										{
											$image = str_replace('.as', '.com', $image);
											$out .= '<br />Uploaded:'.$image;
											echo '<br />Uploaded:'.$image;
											
											$adc->CurrentAd->uploadImage($image);
											$adc->CurrentAd->setItemLoaded('images', false);
										}
									}
								}
								
								if((self::getAutoPublish() > 0) && ($adc->CurrentAd->getActive() == 0))
								{ 
									$adc->CurrentAd->Publish(); 
									$out .= '<br />Prospect Published';
								}
								
								$out .= '<hr />';
								//print_r($adc->CurrentAd);
							}
							$adc->setCurrentAdId(0);
						}
					}
					//print_r($deleteUserAds);
					if(isset($deleteUserAds))
					{
						if(is_array($deleteUserAds))
						{ $out .= self::deleteExcluded($deleteUserAds); }
					}
				} //if($adListAds)
			}
		}
		$out .= '<br />Found:'.self::getFound();
		$out .= '<br />Imported:'.self::getImported();
		$out .= '<br />Updated:'.self::getUpdated();
		$out .= '<br />Failed:'.(self::getFound() - (self::getUpdated() + self::getImported()));
		$out .= '<br />FEED IMPORT COMPLETE<hr />';
		return $out;
	}
	
	function checkIfExists($newAd)
	{
		$id = 0;
		global $adc;
		global $db;
		if($newAd->getRemoteId() > 0)
		{
			$sql  = 'SELECT ad.* ';
			$sql .= 'FROM '.DB_PERFIX.'am_ads AS ad ';
			$sql .= 'WHERE ad.id > 0';
			$sql .= ' AND ad.RemoteId='.$newAd->getRemoteId();
			$sql .= ' AND ad.userId='.$newAd->getUserId();
			$sql .= ' AND `deleted`=0';
			$sql .= ' ORDER BY `archived` ASC LIMIT 1;';
			$result = $db->query($sql);
			$data = $db->fetch($sql, 0);
			//echo '<br />'.$sql;
			if(is_array($data))
			{
				foreach($data as $row)
				{ 
					if($row['id'] > 0)
					{ $id = $row['id']; }
				}
			}
		}
		if($id > 0)
		{
			//Clear old ads with same ID
			$this->Out .= '<br />Checking for old ads with remote ID:'.$newAd->getRemoteId();
			$deleted = 0;
			
			$sql  = 'SELECT * ';
			$sql .= 'FROM '.DB_PERFIX.'am_ads ';
			$sql .= 'WHERE `id` > 0';
			$sql .= ' AND `RemoteId` ='.$newAd->getRemoteId();
			$sql .= ' AND `userId` ='.$newAd->getUserId();
			$sql .= ' AND `id` != '.$id;
			$sql .= ' AND `archived` = 0';
			$sql .= ' AND `deleted` = 0';
			$sql .= ' ORDER BY `id`;';
			$result = $db->query($sql);
			$data = $db->fetch($sql, 0);
			if(is_array($data))
			{
				foreach($data as $row)
				{ 
					if($row['id'] > 0)
					{ $delete[$row['id']] = $row['id']; }
				}
			}
			if(is_array($delete))
			{
				echo '<br />'.$sql;
				echo '<br />Ads to remove:';
				echo '<br />Deleting duplicate userAds with RemoteID:'.$newAd->getRemoteId().' <br />count:'.count($delete).'<br />';
				print_r($delete);
				self::deleteExcluded($delete);
			}
			//echo '<br />Found'.count($userAds).' $userAds';
			
		}
		return intval($id);
	}
	
	function findBrandId($newAd)
	{
		global $adc;
		$BrandId = 0;
		
		$brands = $adc->getAdBrands();
		$naBrand = strtolower(trim($newAd->getBrandTitle()));
		$title = $newAd->getBrandTitle();
		$title = str_replace('&Atilde;', 'A', $title);
		$title = str_replace('&yen;', 'y', $title);
		$title = str_replace('Ã', 'a', $title);
		$title = str_replace('¥', 'y', $title);
		$title = str_replace('&Atilde;Â˜veraasen', 'Averaasen', $title);
		$title = str_replace('Kopper&Atilde;&yen;', 'Kopperay', $title);
		
		$newAd->setBrandTitle($title);
		//echo '<br/>$naBrand:'.$naBrand;
		if(trim($newAd->getBrandTitle()) != '')
		{
			foreach($brands as $brand)
			{
				$brandTitle = strtolower(trim($brand->getTitle()));
				if($brandTitle == $naBrand)
				{ $newAd->setBrandId($brand->getId()); }
				
				if($newAd->getBrandId() == 0) 
				{
					if($brandTitle == self::formatText($naBrand))
					{ $BrandId = $brand->getId(); }
				}
			}
			if($BrandId == 0) 
			{
				foreach($brands as $brand)
				{
					if(strtolower(trim($brand->getTitle())) == strtolower(trim($newAd->getBrandTitle())))
					{ $BrandId = $brand->getId(); }
				}
			}
			if($BrandId == 0) 
			{
				foreach($brands as $brand)
				{
					if((substr_count(strtolower(trim($brand->getTitle())), strtolower(trim($newAd->getBrandTitle()))) > 0) || 
					   (substr_count(strtolower(trim($newAd->getBrandTitle())), strtolower(trim($brand->getTitle()))) > 0))
					{ $BrandId = $brand->getId(); }
				}
			}
			if(($BrandId == 0) && (str_word_count($newAd->getBrandTitle()) == 1)) 
			{
				if($adc->getSetting('BrandImport') > 0)
				{
					$title = trim($newAd->getBrandTitle());
					$title = strtolower($title);
					$title = ucwords($title);
					if(preg_match('/[a-zA-Z]/',$title))
					{
						$brand = new AdBrand();
						$brand->setTitle($title);
						$BrandId = $brand->Insert();
					}
				}
			}
		}
		if($BrandId == 0) 
		{
			$this->Out .= '<br />-Brand setting to Other'; 
			foreach($brands as $brand)
			{
				if(substr_count(strtolower(trim($brand->getTitle())), strtolower(trim('Andre'))) > 0)
				{ 
					$BrandId = $brand->getId();
					//echo '<br />$brandTitle:'.$brandTitle;
				}
			}
			if($BrandId > 0) 
			{ echo '<br />-Brand setting to Other couldnt find:'.$newAd->getBrandTitle(); }
		}
		if($BrandId == 0) 
		{  echo '<br />-Brand:'.$newAd->getBrandTitle().' Not found'; }
		return intval($BrandId);
	}
	
	function deleteExcluded($deleteUserAds)
	{
		if(count($deleteUserAds) > 0)
		{
			global $adc;
			$out .= '<br />Deleting '.count($deleteUserAds).' ads:';
			echo '<br />Deleting '.count($deleteUserAds).' ads:';
			$deleted = 0;
			$userAds = $this->UserAds;
			
			$out .= '<br />Found '.count($this->UserAds).' $userAds';
			echo '<br />Found '.count($this->UserAds).' $userAds:<br />';
			foreach($deleteUserAds as $da)
			{
				echo '<br />Checking for user ad:'.$da;
			    echo '<br />is_object($this->UserAds['.$da.']):'.is_object($this->UserAds[$da]);
				
				if(is_object($this->UserAds[$da]))
				{
					$out .= '<br />Deleting ad ID:'.$this->UserAds[$da]->getId();
					echo '<br />Deleting ad ID:'.$this->UserAds[$da]->getId();
					$this->UserAds[$da]->setDeleted(1);
					$this->UserAds[$da]->setDataChanged(1);
					$this->UserAds[$da]->deleteImages();
					$this->UserAds[$da]->update();
					$deleted++;
				}
			}
		}
		$out .= '<br />Deleted:'.$deleted;
		return $out;
	}
	
	function findTypeCatId($params)
	{
		if(is_array(self::getImportConverts()))
		{
			if($params['RemoteTypeId'] > 0)
			{
				if($params['RemoteCatId'] > 0)
				{
					foreach(self::getImportConverts() as $ic)
					{
						if(($ic['ConversionType'] == 2) && ($params['RemoteTypeId'] == $ic['RemoteTypeId']) && ($params['RemoteCatId'] == $ic['RemoteCatId']))
						{
							$params['TypeId'] = $ic['ToTypeId'];
							$params['CatId'] = $ic['ToCatId'];
							return $params;
						}
					}
				}
				else
				{
					foreach(self::getImportConverts() as $ic)
					{
						if(($ic['ConversionType'] == 2) && ($params['RemoteTypeId'] == $ic['RemoteTypeId']))
						{
							$params['TypeId'] = $ic['ToTypeId'];
							return $params;
						}
					}
				}
			}
			else
			{
				if($params['RemoteCatId'] > 0)
				{
					foreach(self::getImportConverts() as $ic)
					{
						if(($ic['ConversionType'] == 2) && ($params['RemoteCatId'] == $ic['RemoteCatId']))
						{
							$params['CatId'] = $ic['ToCatId'];
							return $params;
						}
					}
				}
			}
		}
		return $params;
	}
	
	function convertXml($xmlStr)
	{
		if((is_array(self::getImportConverts())) && ($xmlStr != ''))
		{
			$xmlConvertStr = $xmlStr;
			foreach(self::getImportConverts() as $ic)
			{
				$search[0] = '';
				$replace[0] = '';
				
				$search[1] = '';
				$replace[1] = '';
				
				$search[2] = '';
				$replace[2] = '';
				
				if($ic['ConversionType'] == 0)
				{
					if(($ic['FieldFrom'] != '') && ($ic['FieldFrom'] != $ic['FieldTo']))
					{
						$search[0] = '<'.$ic['FieldFrom'].'>';
						$replace[0] = '<'.$ic['FieldTo'].'>';
						
						$search[1] = '</'.$ic['FieldFrom'].'>';
						$replace[1] = '</'.$ic['FieldTo'].'>';
						
						$search[2] = '<'.$ic['FieldTo'].'></'.$ic['FieldTo'].'>';
						$replace[2] = '';
					}
				}
				if(($search[0] != '') && ($replace[0] != $search[0]))
				{ $xmlConvertStr = str_replace($search[0], $replace[0], $xmlConvertStr); }
				if(($search[1] != '') && ($replace[1] != $search[1]))
				{ $xmlConvertStr = str_replace($search[1], $replace[1], $xmlConvertStr); }
				if(($search[2] != '') && ($replace[2] != $search[2]))
				{ $xmlConvertStr = str_replace($search[2], $replace[2], $xmlConvertStr); }
			}
			
			$xmlConvertStr = str_replace('<RemoveString>', '', $xmlConvertStr);
			$xmlConvertStr = str_replace('</RemoveString>', '', $xmlConvertStr);
			
			foreach(self::getImportConverts() as $ic)
			{
				$search[0] = '';
				$replace[0] = '';
				
				$search[0] = '<br />';
				$replace[0] = ' ';
				
				if($ic['ConversionType'] == 1)
				{
					if(($ic['ValueFieldReplace'] != '') && ($ic['ValueFrom'] != '') && ($ic['ValueFrom'] != $ic['ValueTo']))
					{
						$search[0] = '<'.$ic['ValueFieldReplace'].'>'.$ic['ValueFrom'].'</'.$ic['ValueFieldReplace'].'>';
						$replace[0] = '<'.$ic['ValueFieldReplace'].'>'.$ic['ValueTo'].'</'.$ic['ValueFieldReplace'].'>';
					}
				}
				if(($search[0] != '') && ($replace[0] != $search[0]))
				{ $xmlConvertStr = str_replace($search[0], $replace[0], $xmlConvertStr); }
				
				if(($search[1] != '') && ($replace[1] != $search[1]))
				{ $xmlConvertStr = str_replace($search[1], $replace[1], $xmlConvertStr); }
			}
			$xmlStr = $xmlConvertStr;
		}
		return $xmlStr;
	}
	
	function convertHtml($htmlSource)
	{
		if((is_array(self::getImportConverts())) && ($htmlSource != ''))
		{
			//$ObjArray['AdList']['Ad'] = array();
			$html = new simple_html_dom();
			$html->load($htmlSource);
			$xmlConvertStr = '';
			
			foreach(self::getImportConverts() as $ic)
			{
				$search[0] = '';
				$replace[0] = '';
				
				$search[1] = '';
				$replace[1] = '';
				
				$search[2] = '';
				$replace[2] = '';
				
				if($ic['ConversionType'] == 0)
				{
					if(($ic['FieldFrom'] != '') && ($ic['FieldFrom'] != $ic['FieldTo']))
					{
						$fieldHTML = $html->find($ic['FieldFrom']);
						switch($ic['ValidType'])
						{
							case 'txt':
								$fieldContent = $fieldHTML[0]->plaintext;
							break;
							case 'children':
								$fieldContent = $fieldHTML[0]->children;
							break;
							default:
								$fieldContent = $fieldHTML[0]->innertext;
							break;
						}
						
						switch($ic['ValidType'])
						{
							case 'txt':
								$ObjArray['AdList']['Ad'][$ic['FieldTo']] = trim($fieldContent);
							break;
							case 'int':
								$ObjArray['AdList']['Ad'][$ic['FieldTo']] = intval(preg_replace("/[^0-9]/", '', $fieldContent));
							break;
							case 'children':
								if($fieldContent)
								{
									$i = 0;
									foreach($fieldContent as $param)
									{
										$fieldName= '';
										$fieldValue = '';
										switch($ic['FieldTo'])
										{
											case 'Parameters':
												switch($param->tag)
												{
													case 'dl':
														$fields = $param->children;
														if($fields)
														{
															foreach($fields as $field)
															{
																switch($field->tag)
																{
																	case 'dt':
																		$fieldName = $field->plaintext;
																	break;
																	case 'dd':
																		$fieldValue = $field->plaintext;
																	break;
																}
															}
														}
													break;
												}
												if(($fieldName != '') && ($fieldValue != ''))
												{ $ObjArray['AdList']['Ad'][$ic['FieldTo']][$fieldName] = $fieldValue; }
											break;
											case 'ImageParameters':
												if($param->$ic['ValueFrom'])
												{ $ObjArray['AdList']['Ad']['ImagesURL'][$i] = $param->$ic['ValueFrom']; }
											break;
											default:
												if(($fieldName != '') && ($fieldValue != ''))
												{ $ObjArray['AdList']['Ad'][$ic['FieldTo']][$fieldName] = $fieldValue; }
											break;
										}
										$i++;
									}
								}
							break;
							default:
								$ObjArray['AdList']['Ad'][$ic['FieldTo']] = $fieldContent;
							break;
						}
						
					}
				}
			}
			
			foreach(self::getImportConverts() as $ic)
			{
				$search[0] = '';
				$replace[0] = '';
				
				$search[0] = '<br />';
				$replace[0] = ' ';
				
				$search[1] = '<hr />';
				$replace[1] = '';
				
				$search[2] = '  ';
				$replace[2] = ' ';
				
				if($ic['ConversionType'] == 1)
				{
					if(($ic['ValueFieldReplace'] != '') && ($ic['ValueFrom'] != '') && ($ic['ValueFrom'] != $ic['ValueTo']))
					{
						$search[0]  = $ic['ValueFrom'];
						$replace[0] = $ic['ValueTo'];
					}
					if(($ic['ValueFieldReplace'] != '') && ($ic['FieldFrom'] != '') && ($ic['FieldTo'] != ''))
					{
						switch($ic['ValidType'])
						{
							case 'txt':
								$ObjArray['AdList']['Ad'][$ic['FieldTo']] = $ObjArray['AdList']['Ad'][$ic['ValueFieldReplace']][$ic['FieldFrom']];
							break;
							case 'int':
								$ObjArray['AdList']['Ad'][$ic['FieldTo']] = intval(preg_replace("/[^0-9]/", '', $ObjArray['AdList']['Ad'][$ic['ValueFieldReplace']][$ic['FieldFrom']]));
							break;
							case 'bool':
							case 'yes-no':
								if($ObjArray['AdList']['Ad'][$ic['ValueFieldReplace']][$ic['FieldFrom']])
								{ $ObjArray['AdList']['Ad'][$ic['FieldTo']] = 1; }
							break;
							default:
								$ObjArray['AdList']['Ad'][$ic['FieldTo']] = $ObjArray['AdList']['Ad'][$ic['ValueFieldReplace']][$ic['FieldFrom']];
							break;
						}
						unset($ObjArray['AdList']['Ad'][$ic['ValueFieldReplace']][$ic['FieldFrom']]);
					}
				}
				
				if(($search[0] != '') && ($replace[0] != $search[0]))
				{ 
					$xmlConvertStr = str_replace($search[0], $replace[0], $xmlConvertStr); 
					$ObjArray['AdList']['Ad'][$ic['ValueFieldReplace']] = str_replace($search[0], $replace[0], $ObjArray['AdList']['Ad'][$ic['ValueFieldReplace']]);
					
					if(($search[1] != '') && ($replace[1] != $search[1]))
					{ 
						$xmlConvertStr = str_replace($search[1], $replace[1], $xmlConvertStr); 
						$ObjArray['AdList']['Ad'][$ic['ValueFieldReplace']] = str_replace($search[1], $replace[1], $ObjArray['AdList']['Ad'][$ic['ValueFieldReplace']]);
					}
					if(($search[2] != '') && ($replace[2] != $search[2]))
					{ 
						$xmlConvertStr = str_replace($search[2], $replace[2], $xmlConvertStr); 
						$ObjArray['AdList']['Ad'][$ic['ValueFieldReplace']] = str_replace($search[2], $replace[2], $ObjArray['AdList']['Ad'][$ic['ValueFieldReplace']]);
					}
				}
			}
		}
		return $ObjArray;
	}
	
	function loadImportConverts()
	{
		if(!self::getItemLoaded('ImportConverts'))
		{
			global $db;
			$sql  = 'SELECT * ';
			$sql .= 'FROM '.DB_PERFIX.'am_ImportConverts ';
			
			$sql .= 'WHERE ImportId='.self::getId();
			$sql .= ' ORDER BY ConversionType ASC, Id ASC;';
			
			$result = $db->query($sql);
			$data = $db->fetch($sql, 0);
			if(is_array($data))
			{
				foreach($data as $row)
				{ $this->ImportConverts[$row['Id']] = $row; }
			}
			unset($data);
			self::setItemLoaded('ImportConverts', true);
		}
	}
	
	function insert()
	{
		global $user;
		if((self::getUserId() > 0) && (self::getURL() != ''))
		{
			$insert = '`UserId`';
			$values = self::getUserId();
			
			$insert .= ', `Frequency`';
			$values .= ', '.self::getFrequency();

			$insert .= ', `URL`';
			$values .= ", '".self::getURL()."'";
			
			$insert .= ', `DateCreated`';
			$values .= ', NOW()';
			
			$insert .= ', `DateLastRun`';
			$values .= ', NOW()';
			
			$insert .= ', `Active`';
			$values .= ', '.self::getActive();
			
			$sql  = 'INSERT INTO '.DB_PERFIX.self::getDataTable().' ('.$insert.') '; 
			$sql .= 'VALUES ('.$values.');';
			$result = mysql_query($sql);

			$sql = 'SELECT id FROM '.DB_PERFIX.self::getDataTable().' WHERE `userId`='.self::getUserId().' ORDER BY id DESC LIMIT 1;';
			$result = mysql_query($sql);
			if(mysql_num_rows($result) > 0)
			{
				while($row = mysql_fetch_array($result))
				{ self::setId($row['id']); }
			}
		}
	}
	
	function update()
	{
		if((self::getId() > 0) && (self::getDataChanged()))
		{
			$sql  = 'UPDATE '.DB_PERFIX.self::getDataTable().' SET ';
			$sql .= '`UserId`='.self::getUserId().', ';
			$sql .= '`Frequency`='.self::getFrequency().', ';
			$sql .= '`DateLastRun`="'.self::getDateLastRun().'", ';
			$sql .= "`URL`='".self::getDateLastRun()."', ";
			$sql .= '`Active`='.self::getActive().' ';
			$sql .= ' WHERE Id='.self::getId().' LIMIT 1;';
			mysql_query($sql);
		}
	}
}
?>